package com.ticket.dao;


import com.ticket.entity.Order;
import com.ticket.entity.Ticket;
import com.ticket.util.FileUtil;

import java.util.HashMap;
import java.util.Map;

public class TicketDao {

    private FileUtil fileUtil = new FileUtil();

    /**
     * 将余票对象解析为字符串
     * @param ticketMap
     * @return
     */
    public String mapToString(Map<Integer,Ticket> ticketMap){
        StringBuffer ticketString = new StringBuffer();
        for (Integer key : ticketMap.keySet()){
            Ticket ticket = ticketMap.get(key);
            ticketString.append(key + "           ");
            ticketString.append(ticket.getStartStation() + "           ");
            ticketString.append(ticket.getEndStation() + "           ");
            ticketString.append(ticket.getCount() + "\n");
        }
        return ticketString.toString().trim();
    }

    /**
     * 将字符串解析为余票对象
     * @param ticketString
     * @return
     */
    public Map<Integer,Ticket> stringToMap(String ticketString){
        String [] ticketArray = ticketString.split("\n");
        Map<Integer, Ticket> ticketMap = new HashMap<>();
        for( String ticketStr : ticketArray){
            Ticket ticket = new Ticket();
            String [] ticketInfo = ticketStr.split("           ");
            ticket.setTicketId(Integer.valueOf(ticketInfo[0]));
            ticket.setStartStation(ticketInfo[1]);
            ticket.setEndStation(ticketInfo[2]);
            ticket.setCount(Integer.valueOf(ticketInfo[3]));
            ticketMap.put(ticket.getTicketId(),ticket);
        }
        return ticketMap;
    }

    /**
     * 获取所有余票信息
     * @return
     */
    public Map<Integer, Ticket> getAllTicket(){
       String ticketString = fileUtil.getContent("ticket.txt");
       if(ticketString == null){
           return null;
       }else {
           return this.stringToMap(ticketString);
       }
    }

    /**
     * 更新所有余票信息
     * @param ticketMap
     */
    public void saveAllTicket(Map<Integer,Ticket> ticketMap){
        String ticketString = this.mapToString(ticketMap);
        fileUtil.saveContent("ticket.txt",ticketString);
    }
}
